package com.myNetty;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class MyEventLoopGroup implements EventLoopGroup{

    private EventLoop[] child;

    private AtomicInteger index = new AtomicInteger(0);

    public MyEventLoopGroup(int capacity){
        child = new EventLoop[capacity];
        for(int i=0;i<capacity;i++){
            child[i] = new MyEventLoop();
        }
    }

    @Override
    public void execute(Runnable runnable) {
        if(runnable instanceof TargetTask targetTask){
            child[targetTask.getIndex()].execute(runnable);
        }
        next().execute(runnable);
    }

    @Override
    public void scheduleAtFixedRate(Runnable task, long initialDelay, long period, TimeUnit unit) {
        next().scheduleAtFixedRate(task, initialDelay, period, unit);
    }

    @Override
    public void schedule(Runnable task, long delay, TimeUnit unit) {
        next().schedule(task, delay, unit);
    }

    @Override
    public EventLoop next() {
        return child[index.getAndIncrement() % child.length];
    }
}
